//
//  ConLoginViewController.m
//  Shengzhuli
//
//  Created by FXGuo on 2017/4/17.
//  Copyright © 2017年 kamangkeji. All rights reserved.
//

#import "ConLoginViewController.h"
#import "VefityTool.h"
#import "MBProgressHUD+MJ.h"
#import "LoginRegisterService.h"
#import "ConActivityDetailController.h"
#import "SZLAccountHelper.h"
#import <EMSDK.h>
#import "ChatDemoHelper.h"
#import "LoginInfoController.h"
#import "JPUSHService.h"
#import "PersonNetWork.h"

@interface ConLoginViewController ()

@property (weak, nonatomic) IBOutlet UITextField *tellField;
@property (weak, nonatomic) IBOutlet UITextField *codeField;
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

@property (weak, nonatomic) IBOutlet UIButton *protocolBtn;

@property (nonatomic,strong) NSTimer *timer;
@property (nonatomic,assign) NSInteger count;

@end

@implementation ConLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGBColor(239, 239, 244);
    self.title = @"快捷登录";
    self.count = 60;
    [self setNavi];
}
- (IBAction)btnClick:(UIButton *)btn
{
    switch (btn.tag) {
        case 0:
        {
            [self getCode];
        }
            break;
        case 1:
        {
            [self getLoginRegister];
        }
            break;
        case 2:
        {
            btn.selected = !btn.selected;
        }
            break;
        case 3:
        {
            ConActivityDetailController *webVc = [[ConActivityDetailController alloc]init];
            webVc.type = WebTypeRegister;
            [self.navigationController pushViewController:webVc animated:YES];
        }
            break;
        default:
            break;
    }
}
- (IBAction)textChanged:(UITextField *)field
{
    if (field.tag == 0) {
        self.codeBtn.enabled = (self.tellField.text.length == 11 && self.count == 60);
    }
    self.loginBtn.enabled = (self.tellField.text.length == 11 && self.codeField.text.length == 6);
}

- (void)setNavi
{
    UIButton *backBtn = [[UIButton alloc]init];
    backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [backBtn setBackgroundImage:[UIImage imageNamed:@"back_black"] forState:UIControlStateNormal];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"back_black"] forState:UIControlStateHighlighted];
    [backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [backBtn sizeToFit];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
}
- (void)backClick
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)getLoginRegister
{
    if (![VefityTool isValidTellNumber:self.tellField.text]) {
        [MBProgressHUD showError:@"请输入正确的手机号码" toView:self.view];
        return;
    }
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"mobilePhone"] = self.tellField.text;
    parame[@"smsCode"] = self.codeField.text;
    [self showClearBgWaiter];
    [LoginRegisterService loginRegisterWithParame:parame response:^(BOOL success, NSString *msg) {
        [self hideWaiter];
        if (success) {
            [MBProgressHUD showSuccess:@"登录成功" toView:self.view];
            [[NSNotificationCenter defaultCenter]postNotificationName:UserLogined object:nil];
            [self getPersonInfo];
//            //在此登录环信
//            [[EMClient sharedClient] loginWithUsername:[SZLAccountHelper shareInstance].mobilePhone password:[SZLAccountHelper shareInstance].HXpwd completion:^(NSString *aUsername, EMError *aError) {
//                if (!aError) {
//                    NSLog(@"环信登录成功");
//                    [[EMClient sharedClient].options setIsAutoLogin:YES];
//                    [[ChatDemoHelper shareHelper] asyncGroupFromServer];
//                    [[ChatDemoHelper shareHelper] asyncConversationFromDB];
//                    [[ChatDemoHelper shareHelper] asyncPushOptions];
//                }else {
//                    NSLog(@"%zd  --  %@",aError.code,aError.errorDescription);
//                }
//            }];
            //极光设置别名
            [JPUSHService setAlias:[SZLAccountHelper shareInstance].mobilePhone completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
                NSLog(@"别名设置是否成功%zd",iResCode);
            } seq:1000000];
            if ([SZLAccountHelper shareInstance].token.length<1) {
                LoginInfoController *infoVc = [[LoginInfoController alloc]init];
                [self.navigationController pushViewController:infoVc animated:YES];
                return ;
            }
        }else{
            [MBProgressHUD showError:msg toView:self.view];
        }
    }];
}
- (void)getCode
{
    if (![VefityTool isValidTellNumber:self.tellField.text]) {
        [MBProgressHUD showError:@"请输入正确的手机号码" toView:self.view];
        return;
    }
    [self.view endEditing:YES];
    [self showClearBgWaiter];
    [LoginRegisterService getVerfyCodeWithParame:@{@"mobilePhone":self.tellField.text} response:^(BOOL success, NSString *msg) {
        [self hideWaiter];
        if (success) {
            [MBProgressHUD showSuccess:@"验证码获取成功" toView:self.view];
            self.codeBtn.enabled = NO;
            [self.timer fire];
            [self.codeField becomeFirstResponder];
        }else{
            [MBProgressHUD showError:msg toView:self.view];
        }
    }];

}

- (void)getPersonInfo
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    [self showWaiter];
    [PersonNetWork getPersonInfoWithParame:parame response:^(BOOL success, NSString *msg,NSString *errorCode,PersonInfo *info) {
        [self hideWaiter];
        [self hideReloadView];
        if (success) {
            [SZLAccountHelper shareInstance].name = info.name;
        }else{
            if ([msg isEqualToString:NetworkError]) {
                [self showReloadViewWithTarget:self action:@selector(getPersonInfo)];
            }
            [MBProgressHUD showError:msg toView:self.view];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if ([errorCode isEqualToString:NoLoginStatus]) {
                    [self.navigationController popToRootViewControllerAnimated:YES];
                    SZLTabBarViewController *barVc = (SZLTabBarViewController*)[UIApplication sharedApplication].keyWindow.rootViewController;
                    barVc.selectedIndex = 0;
                    [SZLAccountHelper clearAlreadyInfo];
                    [SZLAccountHelper shouldLogin];
                }
            });
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self dismissViewControllerAnimated:YES completion:nil];
        });
    }];
}


- (void)timeDown
{
    self.count--;
    if (self.count <= 0) {
        [self endTimer];
        self.codeBtn.enabled = YES;
        [self.codeBtn setTitle:@"重新获取" forState:UIControlStateNormal];
        self.count = 60;
        return;
    }
    [self.codeBtn setTitle:[NSString stringWithFormat:@"%zd",self.count] forState:UIControlStateNormal];
}
- (void)endTimer
{
    [self.timer invalidate];
    self.timer = nil;
}
- (NSTimer *)timer
{
    if (!_timer) {
        _timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timeDown) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop]addTimer:_timer forMode:NSRunLoopCommonModes];
    }
    return _timer;
}


@end
